package com.shaoshaohuo.app.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.GridViewAdapter;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.net.ShopHttpConfig;
import com.shaoshaohuo.app.utils.BitmapUtils;
import com.shaoshaohuo.app.utils.CircleImageView;
import com.shaoshaohuo.app.utils.FiveCornerStar;
import com.shaoshaohuo.app.utils.Okhttputils;
import com.shaoshaohuo.app.view.FlowLayout;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import okhttp3.Call;
import okhttp3.Response;

public class EvaluateActivity extends BaseActivity implements TextWatcher, View.OnClickListener {
    /**
     * tobar
     */
    private ImageView order_tobar_back;
    private TextView order_tobar_enter;
    private ImageView order_tobar_right;
    private LinearLayout order_layout_topbar_left;
    private TextView order_tobar_right_textView;

    private FlowLayout evalute_type;
    private String[] evalute_data = new String[]{"非常新鲜", "很好吃", "物流快", "服务好", "包装很好", "分量足"};
    private EditText evalute_content;
    private TextView evalute_limit_word;

    private CircleImageView evaluate_shop_picture;
    private FiveCornerStar evaluate_star;
    private TextView evalute_level;
    private TextView evalute_add_picture;
    final StringBuffer sb = new StringBuffer();
    private int maxLength = 50;
    private TextView button;

    private String picture_adress;
    private String level;
    private String catid;
    private List<String> picture_data;
    private List<File> file_data;

    private GridView evalute_gridView;
    private GridViewAdapter adapter;
    private HorizontalScrollView release_shop_horscrolistView;

    private void getIntentData() {
        if (getIntent() != null) {
            picture_adress = (String) getIntent().getExtras().get("picture");
            catid = (String) getIntent().getExtras().get("catid");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);
        getIntentData();
        initView();
        setView();
        requestData();
        initListener();
    }

    private void setView() {
        Picasso.with(this).load(picture_adress).into(evaluate_shop_picture);
    }
//    public OnCallBack onCallBack;
//
//    public void setOnCallBack(OnCallBack onCallBack) {
//        this.onCallBack = onCallBack;
//    }

    private void PostRemark() {
        Log.e("=====", level + "==" + catid + "==" + evalute_content.getText().toString());
        if (evalute_content.getText().toString() == null || evalute_content.getText().toString().length() <= 0 || level.length() <= 0 || level == null) {
            Toast.makeText(this, "请您填写评价信息", Toast.LENGTH_SHORT).show();
        } else {
startLoadingDialog();
            ShopHttpConfig.RemarkPost(this, file_data, catid, level, evalute_content.getText().toString(), new Okhttputils.OkutListener() {
                @Override
                public void error(Call call, IOException e) {

                }

                @Override
                public void error(Call call, int code) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoadingDialog();
                            Toast.makeText(getApplicationContext(), "提交失败,请重新填写", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void suseff(Call call, Response response, Object o) {
                    Log.e("提交成功", "提交成功");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissLoadingDialog();
                            Toast.makeText(getApplicationContext(), "提交成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent();
                            intent.setAction("daifukuan");
                            sendBroadcast(intent);
                            finish();
                        }
                    });

                }
            }, BaseEntity.class);
        }
    }

    public static void tackPic(ArrayList<String> mSelectPath, Intent intent2, int selectedMode, int maxNum) {
//        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
//        int maxNum = 10;
//        Intent intent2 = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大可选择图片数量
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent2.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }

    }

    private ArrayList<String> pathlist = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 5) {
            if (data != null) {
                ArrayList<String> select_more_result = data.getStringArrayListExtra("select_result");
                if (select_more_result != null) {
                    for (int i = 0; i < select_more_result.size(); i++) {
                        String picture = select_more_result.get(i);
                        File zipbit = BitmapUtils.zipbit(picture, getApplicationContext());
//                        File file = new File(picture);
                        file_data.add(zipbit);
                        picture_data.add(zipbit.getAbsolutePath());
                    }
                    if (file_data != null && file_data.size() > 0) {
                        evalute_gridView.setVisibility(View.VISIBLE);
                        release_shop_horscrolistView.setVisibility(View.VISIBLE);
                        if (file_data.size() >= 4) {
                            evalute_add_picture.setVisibility(View.GONE);
                        }
                        adapter = new GridViewAdapter(this, picture_data);
                        horizontal_layout();
                        evalute_gridView.setAdapter(adapter);
                        adapter.setDelete(new GridViewAdapter.Delete() {
                            @Override
                            public void delete() {
                                if (adapter.getCount() < 6) {
                                    evalute_add_picture.setVisibility(View.VISIBLE);
                                }
                            }
                        });
                    }
//                    if (data != null) {
//                        ArrayList<String> select_more_result_e = data.getStringArrayListExtra("select_result");
//                        if (select_more_result_e != null) {
//                            for (int i = 0; i < select_more_result_e.size(); i++) {
//                                String picture = select_more_result_e.get(i);
//                                File file = new File(picture);
//                                file_data.add(file);
//                                picture_data.add(picture);
//                            }
//                            if (file_data != null && file_data.size() > 0) {
//                                evalute_gridView.setVisibility(View.VISIBLE);
//                                release_shop_horscrolistView.setVisibility(View.VISIBLE);
//                                if (file_data.size() >= 4) {
//                                    evalute_add_picture.setVisibility(View.GONE);
//                                }
//                                adapter = new GridViewAdapter(this, picture_data);
//                                horizontal_layout();
//                                evalute_gridView.setAdapter(adapter);
//                                adapter.setDelete(new GridViewAdapter.Delete() {
//                                    @Override
//                                    public void delete() {
//                                        if (adapter.getCount() < 6) {
//                                            evalute_add_picture.setVisibility(View.VISIBLE);
//                                        }
//                                    }
//                                });
//                            }
                }
//                    }
//                }
            }
        }
    }

    public void horizontal_layout() {
        int size = file_data.size();
        DisplayMetrics dm = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int allWidth = (int) (110 * size * density);
        int itemWidth = (int) (100 * density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                allWidth, LinearLayout.LayoutParams.FILL_PARENT);
        evalute_gridView.setLayoutParams(params);// 设置GirdView布局参数
        evalute_gridView.setColumnWidth(itemWidth);// 列表项宽
        evalute_gridView.setHorizontalSpacing(15);// 列表项水平间距
        evalute_gridView.setStretchMode(GridView.NO_STRETCH);
        evalute_gridView.setNumColumns(size);//总长度
    }

    private void initListener() {
        order_tobar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        evalute_add_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                tackPic(pathlist, intent, 1, 6);
                intent.setClass(getApplicationContext(), MultiImageSelectorActivity.class);
                startActivityForResult(intent, 5);
            }
        });
        evaluate_star.setOnCallBackListener(new FiveCornerStar.OnCallBackListener() {
            @Override
            public void onItemClickListener(View view, float num) {
                int numStart = (int) num;
                int numstart = numStart + 1;
                if (numstart == 1) {
                    evalute_level.setText("“还行噢”");
                } else if (numstart == 2) {
                    evalute_level.setText("“很好呀”");
                } else if (numstart == 3) {
                    evalute_level.setText("“很满意”");
                } else if (numstart == 4) {
                    evalute_level.setText("“非常满意”");
                } else if (numstart == 5) {
                    evalute_level.setText("“超级满意”");
                }
                level = numstart + "";
            }
        });
        final String s1 = null;
        evalute_content.addTextChangedListener(this);
        evalute_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                evalute_content.setHint("");
                evalute_content.setCursorVisible(true);
                return false;
            }
        });
        order_tobar_right_textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PostRemark();
            }
        });
    }

    private void requestData() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.setMargins(22, 14, 22, 14);
        for (int i = 0; i < evalute_data.length; i++) {
            button = new TextView(this);
            button.setLayoutParams(params);
            button.setText(evalute_data[i]);
            Drawable drawable = getResources().getDrawable(R.drawable.evaluate_oral);
            button.setBackground(drawable);
            button.setPadding(12, 8, 12, 8);
            button.setGravity(Gravity.CENTER);
            button.setTextSize(13);
            button.setTextColor(getResources().getColor(R.color.color_999999));
            evalute_type.addView(button);
            button.setTag(evalute_data[i]);
            button.setOnClickListener(this);
        }
    }

    private void initView() {
        /**
         * tobar
         * */
        order_tobar_back = (ImageView) findViewById(R.id.imageview_topbar_left_backImage);
        order_tobar_back.setVisibility(View.VISIBLE);
        order_tobar_back.setImageResource(R.mipmap.return_key);
        order_tobar_enter = (TextView) findViewById(R.id.toolbar_topname);
        order_tobar_enter.setText("发表评价");
        order_tobar_right = (ImageView) findViewById(R.id.imageview_message);
        order_tobar_right.setVisibility(View.GONE);
        order_tobar_right_textView = (TextView) findViewById(R.id.textview_message);
        order_tobar_right_textView.setVisibility(View.VISIBLE);
        order_tobar_right_textView.setText("发布");
        order_layout_topbar_left = (LinearLayout) findViewById(R.id.layout_topbar_left);
        order_layout_topbar_left.setVisibility(View.VISIBLE);

        picture_data = new ArrayList<>();
        file_data = new ArrayList<>();
        evalute_type = (FlowLayout) findViewById(R.id.evalute_type);
        evalute_content = (EditText) findViewById(R.id.evalute_content);
        evalute_limit_word = (TextView) findViewById(R.id.evalute_limit_word);

        evaluate_shop_picture = (CircleImageView) findViewById(R.id.evaluate_shop_picture);
        evaluate_star = (FiveCornerStar) findViewById(R.id.evaluate_star);
        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        int width=metrics.widthPixels;
//        int height = metrics.heightPixels;
        evaluate_star.setNum(5);
        evaluate_star.setdownnum(0);
        evaluate_star.setIsdown(true);
        evalute_level = (TextView) findViewById(R.id.evalute_level);
        evalute_add_picture = (TextView) findViewById(R.id.evalute_add_picture);
        evalute_gridView = (GridView) findViewById(R.id.evalute_gridView);
        release_shop_horscrolistView = (HorizontalScrollView) findViewById(R.id.release_shop_horscrolistView);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() > maxLength) {
            Toast.makeText(getApplicationContext(), "字数超出限制", Toast.LENGTH_SHORT).show();
            String newString = s.toString().substring(0, maxLength);
            evalute_content.setText(newString);
            int newLength = evalute_content.getText().length();
            evalute_content.setSelection(newLength);
        } else {
            String trim = evalute_content.getText().toString().trim();
            evalute_limit_word.setText(s.length() + "/50");
        }
    }


    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onClick(View v) {
        String word = evalute_content.getText().toString().trim();
        String text = ((TextView) v).getText().toString();
        evalute_content.setHint("");
        evalute_content.setCursorVisible(true);
        word = word + text + " ";
        if (word.length() > maxLength) {
            Toast.makeText(getApplicationContext(), "字数超出限制", Toast.LENGTH_SHORT).show();
            String newString = word.substring(0, maxLength);
            evalute_content.setText(newString);
            int newLength = evalute_content.getText().length();
            evalute_content.setSelection(newLength);
        } else {
            evalute_content.setText(word);
            evalute_content.setSelection(word.length());
        }
    }

    public interface OnCallBack {
        void onBackMsg(String msg);
    }
}
